
import OSS from "ali-oss";
import path from "path";
import dotenv from 'dotenv';
import fs from 'fs';

// 加载对应环境的env文件
dotenv.config({ path: ".env" });

// console.log("accessKeyId", process.env.accessKeyId);
// console.log("accessKeySecret", process.env.accessKeySecret);
// console.log("region", process.env.region);
// console.log("bucket", process.env.bucket);
// console.log("ossDir", process.env.ossDir);

// 递归读取文件夹内所有文件，包括子目录的文件
function walk(dir: string, fileList: Array<string> = []) {
    const files = fs.readdirSync(path.join(__dirname, dir));
    files.forEach((val: string) => {
        const info = fs.statSync(path.join(__dirname, dir, val));
        if (info.isFile()) {
            fileList.push(path.join(dir, val));
        }
        if (info.isDirectory()) {
            walk(path.join(dir, val), fileList);
        }
    })
    return fileList;
}


(async () => {

    // 配置 OSS 客户端
    const ossClient = new OSS({
        region: process.env.region,
        accessKeyId: process.env.accessKeyId || "",
        accessKeySecret: process.env.accessKeySecret || "",
        bucket: process.env.bucket,
    });

    const localDir = path.join(__dirname, '../dist');
    // 读取本地目录
    const files = walk('../dist', [] as string[]);
    console.log(`开始上传`);
    for (const file of files) {
        // 跳过 node_modules
        if (file.includes('node_modules')) continue;

        const filePath = path.join(__dirname, file as string);
        const stats = fs.statSync(filePath);
        if (stats.isFile()) {
            // 3. 上传文件到OSS
            let ossPath = path.join(__dirname, file as string).replace(/\\/g, '/');
            ossPath = ossPath.replace(localDir.replace(/\\/g, '/'), '');
            ossPath = path.join(process.env.ossDir || "", ossPath).replace(/\\/g, '/');
            console.log(ossPath);
            await ossClient.put(ossPath, fs.createReadStream(filePath));
        }
    }
    console.log(`上传完成`);
})();